<template>
  <div>
    <!-- 套了一个table组件，封装了行 -->
    <MyTable :list="list">
      <template #head>
        <tr>
          <th>#</th>
          <th>商品名称</th>
          <th>价格</th>
          <th>标签</th>
          <th>操作</th>
        </tr>
      </template>
      <!-- 直接解构进行渲染 -->
      <template #body="{row, index}">
        <td>{{ index + 1 }}</td>
        <td>{{ row.goods_name }}</td>
        <td>{{ row.goods_price }}</td>
        <td>
          <!--row.inputVisible决定什么显示
              row.inputValue动态绑定内容
              @blur="row.inputVisible = false;row.inputValue = ''失焦时既要让数据清空也得失去显示控件进行切换  -->
          <input
            type="text"
            v-if="row.inputVisible"
            class="tag-input form-control"
            style="width: 100px"
            v-fff
            v-model="row.inputValue"
            @keydown.enter="addTag(row)"
            @keydown.esc="row.inputValue = ''"
            @blur="row.inputVisible = false;row.inputValue = '' "
          >
          <button
            v-else
            class="btn btn-primary btn-sm add-tag"
            style="display: block;"
            @click="row.inputVisible = true"
          >Tag+1</button>
          <span
            v-for="(str, index) in row.tags"
            :key="index"
            class="badge bg-warning"
          >{{ str }}</span>
        </td>
        <td>
          <button
            class="btn btn-danger btn-sm"
            @click="delFn(row.id)"
          >删除</button>
        </td>
      </template>
    </MyTable>
  </div>
</template>
 
<script>
import MyTable from '@/components/MyTable'
export default {
  components: {
    MyTable
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    // axios请求数据
    this.$axios({
      url: '/api/goods'
    }).then((res) => {
      this.list = res.data.data
    })
  },
  methods: {
    // 通过id去修改原数组达到删除目的
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    // 添加标签
    addTag(obj) {
      if (!obj.inputValue.trim()) return alert('请输入非空内容')
      obj.tags.push(obj.inputValue)
      obj.inputValue = ''
    }
  },
  // 自定义指令
  directives: {
    fff: {
      inserted(el) {
        el.focus()
      }
    }
  }
}
</script>

<style scoped>
</style>